<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth {

	//权限列表
	var $authlist = array(
		'用户管理'=>array(
				"删除用户",
				"修改用户",
				"添加用户",
				"修改权限"
			),
		'合同管理'=>array(
				"添加合同",
				"删除合同",
				"修改合同",
				"审批待审批合同",
				"合同定密",
				"提交科研院审批",
				"最终审批",
				"查看所有合同"
			)
	);
	
	//判断数据库中是否有该用户
	public function hasUser($userid)
	{
		$CI = & get_instance();
		$query = $CI->db->query("SELECT * FROM user WHERE User_ID = '$userid'");
		if ($query->num_rows()>0) return true;
		else return false;
	}
	
	//判断用户是否有$auth指定的权限
    public function hasAuth($userid = "",$auth = "") 
	{
		$CI = & get_instance();
		$query = $CI->db->query("SELECT * FROM userauthority WHERE User_ID = '$userid' AND Auth_Name = '$auth'");
		if ($query->num_rows()>0) return true;
		else return false;
    }
	
	//获取某用户的所有权限
	public function getUserAuth($userid)
	{
		$CI = & get_instance();
		$query = $CI->db->query("SELECT Auth_Name FROM userauthority WHERE User_ID = '$userid'");
		$ret = array();
		foreach($query->result() as $row)
		{
			$ret[] = $row->Auth_Name;
		}
		return $ret;
	}
	
	//更新用户的权限，传入新的权限集合（$userAuth）
	public function setUserAuth($userid,$userAuth)
	{
		$CI = & get_instance();
		$oldAuth = $this->getUserAuth($userid);
		$newAuth = array_values($userAuth);
		foreach($this->authlist as $groupKey => $group)
		{
			foreach($group as $item)
			{
				if (in_array($item,$oldAuth) && !in_array($item,$newAuth))
				{
					$this->delAuth($userid,$item);
				}
				else if (!in_array($item,$oldAuth) && in_array($item,$newAuth))
				{
					$this->addAuth($userid,$item);
				}
			}
		}
	}
	
	//在数据库中添加权限
	public function addAuth($userid = "",$auth = "")
	{
		$CI = & get_instance();
		$query = $CI->db->query("INSERT INTO userauthority VALUES('$userid','$auth')");
		if ($CI->db->affected_rows()==1) return true;
		else return false;
	}
	
	//在数据库中删除特定权限
	public function delAuth($userid = "",$auth = "")
	{
		$CI = & get_instance();
		$query = $CI->db->query("DELETE FROM userauthority WHERE User_ID = '$userid' AND Auth_Name = '$auth'");
		if ($CI->db->affected_rows()==1) return true;
		else return false;
	}
	
	//获取完整的权限列表
	public function getAuthList()
	{
		return $this->authlist;	
	}
}

// END Auth class

/* End of file Auth.php */
/* Location: ./php_application/libraries/Pages.php */